import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import numpy as np

# 检查是否有可用的 GPU，如果有则使用 CUDA
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
print(torch.cuda.is_available())
print(torch.cuda.current_device())
print(torch.cuda.device_count())
print(torch.cuda.get_device_name(0))
print(torch.version.cuda)

# 创建一个简单的神经网络模型
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(10, 50)  # 输入层到隐藏层
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(50, 1)  # 隐藏层到输出层

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x


# 初始化模型并将其移动到 GPU（如果可用）
model = SimpleNet().to(device)

# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# 创建一些简单的数据用于训练
# 输入数据：随机生成的 100 个样本，每个样本有 10 个特征
# 输出数据：随机生成的 100 个目标值
inputs = torch.randn(10000, 10).to(device)
targets = torch.randn(10000, 1).to(device)

# 创建数据加载器
dataset = TensorDataset(inputs, targets)
dataloader = DataLoader(dataset, batch_size=16, shuffle=True)

# 训练模型
num_epochs = 200
for epoch in range(num_epochs):
    model.train()
    for batch_inputs, batch_targets in dataloader:
        # 清空梯度
        optimizer.zero_grad()

        # 前向传播
        outputs = model(batch_inputs)

        # 计算损失
        loss = criterion(outputs, batch_targets)

        # 反向传播
        loss.backward()

        # 更新参数
        optimizer.step()

    print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}")

print("Training finished.")